<template>
  <div>
    <!-- 搜索表单 -->
    <div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="pageParams.sampleCode" placeholder="参数名" />
        </el-col>
        <el-col :span="2">
          <div class="button">
            <el-button link @click="search">查询</el-button>
            <div class="buttonHover">
              <el-button icon="DCaret" link class="btnTwo"></el-button>
              <div class="hover">
                <el-button link style="font-size: 13px;" @click=senior>高级查询</el-button>
                <el-button link style="margin-left: 0;font-size: 13px;" @click="resetQuery">重置查询</el-button>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="2">
          <el-button color="#17B2A2" style="color: white;" @click="examMore">审核</el-button>
        </el-col>
        <el-col :span="2" style="margin-left: -15px;">
          <el-button color="#17B2A2" style="color: white;" @click="getExport">导出EXCEL</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 数据表格 -->
    <div class="table" style="margin-top: 20px;">
      <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%;font-size:13px;" border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="样本编码" align="center" prop="sampleCode" />
        <el-table-column label="出库时间" width="160" align="center" prop="outStockOn" />

        <!-- DNA浓度列 -->
        <el-table-column label="DNA浓度（ng/μL）" width="130" align="center" prop="dnaConsi">
          <template #default="scope">
            <el-input v-model="scope.row.dnaConsi" v-if="scope.row.status === 0 || !scope.row.dnaConsi"
              @change="handleDnaConcentrationChange(scope.row)" placeholder="请输入浓度值" :value="scope.row.dnaConsi || 0" />
            <span v-else>{{ scope.row.dnaConsi }}</span>
          </template>
        </el-table-column>
        <!-- 动态显示的列 -->
        <el-table-column v-if="showDynamicColumns" label="提取时间" width="160" align="center" prop="extractTime">
          <template #default="scope">
            {{ scope.row.extractTime || '' }}
          </template>
        </el-table-column>

        <el-table-column v-if="showDynamicColumns" label="提取人" align="center" prop="createBy">
          <template #default="scope">
            {{ scope.row.createBy || '' }}
          </template>
        </el-table-column>

        <el-table-column v-if="showReviewInfo" label="审核时间" width="160" align="center" prop="modifiedOn" />

        <el-table-column v-if="showReviewInfo" label="审核人" align="center" prop="applyUser" />

        <!-- 状态列 -->
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-button v-if="scope.row.status === 1" text style="color: #00F000;">已审</el-button>
            <el-tooltip content="点击审批" placement="top" effect="light">
              <el-button v-if="scope.row.status === 0" text style="color: #17B3A3;"
                @click="toExam(scope.row)">未审</el-button>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column v-if="showDynamicColumns" label="操作" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.extractTime" type="text" style="color: #17B3A3;" @click="handleEdit(scope.row)">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <page :pageParams="pageParams" :total="total" @size-change="pageChange" @currentChange="handleCurrentChange" />

    <!-- 查询对话框 -->
    <div>
      <el-dialog v-model="dialogVisible" :title=title width="48%" style="height: 360px;">
        <div style="margin-left: 25px;margin-top:20px;">
          <el-form :model="pageParams">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="样本编码">
                  <el-input v-model="pageParams.sampleCode" placeholder="样本编码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核状态">
                  <el-select v-model="pageParams.status" placeholder="审核状态">
                    <el-option label="未审核" value="0" />
                    <el-option label="审核通过" value="1" />
                    <el-option label="审核未通过" value="" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="DNA浓度" style="display: flex;">
                  <el-input v-model="pageParams.dnaConsiStart" class="DNAinput" placeholder="DNA浓度开始" />
                  <span> &nbsp;- &nbsp;</span>
                  <el-input v-model="pageParams.dnaConsi" class="DNAinput" placeholder="DNA浓度结束" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出库时间">
                  <el-date-picker v-model="pageParams.outStockOnStart" type="datetime" placeholder="开始时间"
                    style="width: 100px" />
                  <span> &nbsp;- &nbsp;</span>
                  <el-date-picker v-model="pageParams.outStockOn" type="datetime" placeholder="结束时间"
                    style="width: 100px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="提取时间">
                  <el-date-picker v-model="pageParams.extractTimeStart" type="datetime" placeholder="开始时间"
                    style="width: 100px" />
                  <span> &nbsp;- &nbsp;</span>
                  <el-date-picker v-model="pageParams.extractTime" type="datetime" placeholder="结束时间"
                    style="width: 100px" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核时间">
                  <el-date-picker v-model="pageParams.modifiedOnStart" type="datetime" placeholder="开始时间"
                    style="width: 100px" />
                  <span> &nbsp;- &nbsp;</span>
                  <el-date-picker v-model="pageParams.modifiedOn" type="datetime" placeholder="结束时间"
                    style="width: 100px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="提取人">
                  <el-input v-model="pageParams.createBy" placeholder="提取人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核人">
                  <el-input v-model="pageParams.applyUser" placeholder="审核人" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

        </div>
        <template #footer>
          <div class="dialog-footer" style="margin-top: 15px;">
            <el-button @click="reset">重置</el-button>
            <el-button @click=cancel>取消</el-button>
            <el-button color="#17B2A2" @click="seniorQuery">查询</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 修改对话框 -->
    <div>
      <el-dialog v-model="dialogVisible2" :title=title width="48%" style="height: 300px;">
        <div style="margin-left: 25px;margin-top:20px;">
          <el-form ref="ruleFormRef" :model="amend" :rules="rules" :label-position="labelPosition" label-width="auto">
            <el-form-item label="样本编码" prop="code">
              <el-input v-model="amend.sampleCode" style="width: 90%;" disabled />
            </el-form-item>
            <el-form-item label="DNA浓度（ng/μL）" prop="dna">
              <el-input-number v-model="amend.dnaConsi" @change="handleChange" style="width: 90%;" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer" style="margin-top: 15px;">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button color="#17B2A2" @click="confirmEdit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
</template>

<script lang="ts" setup>

import { nextTick, onMounted, reactive, ref } from 'vue';
import { ComponentSize, ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import page from '@/components/page.vue'
import { donorsinfoCard, donorsinfoDelete, donorsinfoExport, donorsinfoList, donorsinfoSave, donorsinfoShow, donorsinfoUpdate,donorsinfoAllList } from '@/api/donorsinfo';

// 变量：==================================================
const query = reactive({
    t: Date.now(),
    page: 1,
    limit: 10,
    key: ''
})
const tableData = ref([])
const currentRow = ref()
const total = ref(0)
const dialogVisible = ref(false)
// 表单
const title = ref('')
interface RuleForm {
    name: string
    idCard: string
    familyId: number | null
    sex: number
    age: number | null
    remark: string
    telephone: string
    birthday: string
    email: string
    nation: string
    comeFrom: string
    homeAddress: string
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    idCard: '',
    name: '',
    familyId: null,
    sex: 1,
    age: 0,
    telephone: '',
    birthday: '',
    email: '',
    nation: '',
    comeFrom: '',
    homeAddress: '',
    remark: ''

})
const options = ref([])

const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '名称不能为空', trigger: 'blur' },
    ],
    idCard: [
        {
            required: true,
            message: '身份证号不能为空',
            trigger: 'blur',
        },
        {
            pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
            message: '请输入有效的身份证',
            trigger: 'blur'
        }
    ]
})
const familyId = ref()
const size = ref<ComponentSize>('default')
const disabled = ref(false)

// 函数：=========================================
// 生命周期
onMounted(() => {
    getDonorsinfo()
})
// 渲染表格数据
function getDonorsinfo() {
    donorsinfoList(query).then(res => {
        console.log(res, '888');
        tableData.value = res.page.list
        total.value = res.page.totalCount
    })
}
// 查询
function getSearch() {
    query.page = 1
    getDonorsinfo()
}
// 分页
// 切换条数
const sChange = (val: number) => {
    console.log(`切换为每页：${val}条`);
    query.limit = val
    getDonorsinfo()
}
// 切换页数
const pChange = (val: number) => {
    console.log(`第${val}页`);
    query.page = val
    getDonorsinfo()
}
// 新增
function getAdd() {
    dialogVisible.value = true
    title.value = '新增'
    // 重置表单
    nextTick(() => {
        ruleFormRef.value.resetFields()
    })
    donorsinfoAllList().then(res => {
        console.log(res);
        options.value = res.AllList
    })
}
// 导出
function getExport() {
    const key = query.key ? query.key : ''
    // console.log(`query.key 的值是: ${key}`);
    donorsinfoExport(key).then(res => {
        // console.log(res, 'jiuj');
        // 创建一个二进制对象  用来存储Excel文件数据
        let blob = new Blob([res])
        // 利用a标签的下载功能
        const link = document.createElement('a')
        // 创建一个下载链接，并将其赋值给href
        link.href = window.URL.createObjectURL(blob)
        link.target = "_blank"
        // 设置文件名
        let nowTime = new Date()
        link.setAttribute('download', `样本来源_${nowTime.getTime()}.xlsx`)
        // 将a标签添加到页面上
        document.body.appendChild(link)
        // 手动触发点击事件
        link.click()
        // 移除a标签
        document.body.removeChild(link)
    }).catch(err => {
        console.error('导出失败:', err);
        ElMessage.error('导出失败');
    })
}
//编辑
function getUpdate(val: number) {
    dialogVisible.value = true
    title.value = '修改'
    donorsinfoAllList().then(res => {
        console.log(res);
        options.value = res.AllList
    })
    donorsinfoShow(val).then(res => {
        // console.log(res, '99');
        ruleForm.name = res.donorsInfo.name
        ruleForm.idCard = res.donorsInfo.idCard
        ruleForm.familyId = res.donorsInfo.familyId
        ruleForm.remark = res.donorsInfo.remark
        ruleForm.sex = res.donorsInfo.sex
        ruleForm.age = res.donorsInfo.age
        ruleForm.telephone = res.donorsInfo.telephone
        ruleForm.birthday = res.donorsInfo.birthday
        ruleForm.email = res.donorsInfo.email
        ruleForm.nation = res.donorsInfo.nation
        ruleForm.comeFrom = res.donorsInfo.comeFrom
        ruleForm.homeAddress = res.donorsInfo.homeAddress
    })
}
// 表单-确定
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value == '新增') {
                donorsinfoSave(ruleForm).then(res => {
                    // console.log(res, '88');
                    ElMessage.success('添加成功')
                    dialogVisible.value = false
                    getDonorsinfo()
                })
                    .catch(err => {
                        ElMessage.error('添加失败')
                    })
            } else if (title.value == '修改') {
                donorsinfoUpdate(ruleForm).then(res => {
                    // console.log(res, '5');
                    ElMessage.success('修改成功')
                    dialogVisible.value = false
                    getDonorsinfo()
                })
                    .catch(err => {
                        ElMessage.error('添加失败')
                    })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible.value = false

    if (!formEl) return
    formEl.resetFields()
}

// 身份证
function handleBlur() {
    // console.log(111);
    donorsinfoCard(ruleForm.idCard).then(res => {
        // console.log(res);
    })
}

// 删除
function getDelete(val: any) {
    const id = [val]
    ElMessageBox.confirm(
        `确定对[id=${val}]进行[删除]操作？`,
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        donorsinfoDelete(id).then(res => {
            ElMessage.success('删除成功')
            getDonorsinfo()
        })
    })

}

</script>

<style lang="scss" scoped>
.whole {
    .search {
        .btn {
            color: #5d5c5c;
        }

        .btn2 {
            color: #fff;
        }

    }

    :deep .table {
        .el-table thead th {
            background-color: #fff !important;
            color: #909399;
        }

        .cell {
            text-align: center !important;
            font-size: 12px !important;
        }

        .el-butto {
            width: 50px !important;
            padding: 0 !important;
        }

        .el-button.is-text {
            padding: 9px 0 !important;
        }

        .el-button>span {
            color: #17b3a3 !important;
            font-size: 12px;
        }
    }

    :deep .dialog {
        .el-table thead th {
            background-color: #fff !important;
            color: #909399;
        }

        .cell {
            text-align: center !important;
            font-size: 12px !important;
        }
    }
}
</style>